<template>
  <div class="app-container">
    <el-tabs style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);margin-bottom: 50px;" v-model="businessType" type="card" @tab-click="handleClick">
      <el-tab-pane label="使用时长" name="1">
      </el-tab-pane>
      <el-tab-pane label="合同份数" name="2">
      </el-tab-pane>
      <el-tab-pane label="短信条数" name="3">
      </el-tab-pane>
      <div class="list">
        <div
          class="item"
          :class="{active: item.id == platformInfo.id}"
          v-for="item in platformRightsList"
          :key="item.id"
          @click="platformInfo = item"
        >
          <div v-if="businessType=='1'">{{ item.amount }}天</div>
          <div v-if="businessType=='2'">{{ item.amount  }}份</div>
          <div v-if="businessType=='3'">{{ item.amount  }}条</div>
          <div class="money">¥{{ item.price }}</div>
          <div v-if="businessType=='1'">{{ (item.price / item.amount).toFixed(4)  }}元/天</div>
          <div v-if="businessType=='2'">{{ (item.price / item.amount).toFixed(4)  }}元/份</div>
          <div v-if="businessType=='3'">{{ (item.price / item.amount).toFixed(4)  }}元/条</div>
          <div v-if="businessType == '1'" class="tips u-m-t-6">赠送合同份数{{ item.giftContract }}份</div>
          <div v-if="businessType == '1'" class="tips">赠送短信条数{{ item.giftSms }}条</div>
        </div>
      </div>
      <div class="actions">
        <div>
          <el-checkbox v-model="checked"></el-checkbox>
          我已阅读并知晓<el-link type="primary" @click="look">《服务套餐购买协议》</el-link>
        </div>
        <div class="">
          <span v-if="platformInfo.id" class="money" style="margin-right: 48px;">{{ platformInfo.price }}元</span>
          <el-button type="primary" @click="payPlatform">立即购买</el-button>
        </div>
      </div>
    </el-tabs>

    <el-table v-loading="loading" :data="platformRightsOrderList">
      <el-table-column :formatter="defaultTableColumnDate" width="200" label="订单编号" align="center" prop="orderNumber" />
      <el-table-column :formatter="defaultTableColumnDate" label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="订单金额" align="center" prop="amount" />
      <el-table-column :formatter="defaultTableColumnDate" label="套餐类型" align="center" prop="rightsName" />
      <el-table-column :formatter="defaultTableColumnDate" label="手机号码" align="center" prop="phone" />
      <el-table-column :formatter="defaultTableColumnDate" label="支付方式" align="center" prop="payType">
        <template slot-scope="scope">
          {{ payTypeInfo[scope.row.payType] }}
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ statusInfo[scope.row.status] }}
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台权益订单对话框 -->
    <el-dialog destroy-on-close title="选择支付方式" :visible.sync="open" width="800px" append-to-body>
      <div class="pay-type" v-if="!code">
        <img :src="wx" alt="" @click="getCode('1')">
        <img :src="zfb" alt="" @click="getCode('2')">
      </div>
      <div class="pay-type" v-if="code">
        <img :src="code" alt="">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qrcode from 'qrcode'
import { listPlatformRightsOrder, platformRightsGetList, payOrder, getPlatformRightsOrder } from "@/api/system/platformRightsOrder";
import { listOperationSystemConfig } from "@/api/system/operationSystemConfig";
import wx from '../../../assets/images/wx.png'
import zfb from '../../../assets/images/zfb.png'

let interval = null

export default {
  name: "PlatformRightsOrder",
  data() {
    return {
      wx,
      zfb,
      code: '',
      statusInfo: {
        '1': '待支付',
        '2': '已支付',
        '3': '已取消',
      },
      payTypeInfo: {
        '1': '微信',
        '2': '支付宝',
      },
      platformInfo: {},
      checked: false,
      platformRightsList: [],
      businessType: '1',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台权益订单表格数据
      platformRightsOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        rightsId: null,
        enterpriseId: null,
        amount: null,
        payType: null,
        status: null,
        payTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      orderCode: '',
      purchaseAgreement: '',
    };
  },
  created() {
    this.getList();
    this.getplatformRightsList();
    listOperationSystemConfig(this.queryParams).then(response => {
      if(response.rows.length) {
        this.purchaseAgreement = this.baseUrl + response.rows[0].purchaseAgreement;
      } else {
        this.purchaseAgreement = ''
      }
    });
  },
  methods: {
    look() {
      if(this.purchaseAgreement) {
        window.open(this.purchaseAgreement)
      } else {
        this.$modal.msg('未查询到《服务套餐购买协议》，请联系系统管理员')
      }
    },
    getCode(payType) {
      this.$modal.loading();
      payOrder({ payType, rightsId: this.platformInfo.id }).then(res => {
        this.$modal.closeLoading();
        this.orderCode = res.orderId
        if(payType=='2') {
          const div = document.createElement('divform');
          div.innerHTML = res.path;
          document.body.appendChild(div);  
          // document.forms['punchout_form'].setAttribute('target', '_blank')
          document.forms['punchout_form'].submit()
        } else {
          qrcode.toDataURL(res.path, {width: 200, height: 200}, (err, url) => {
            if (err) {
              this.$modal.msg('微信支付码生成失败')
            } else {
              this.code = url
            }
          });
        }
        this.getOrderStatus()
      })
    },
    getOrderStatus() {
      let time = 0
      const that = this
      interval = setInterval(async () => {
        const res = await getPlatformRightsOrder(that.orderCode)
        if(res.code == 200) {
          const data = res.data
          if(data.status == '2') {
            that.$modal.msgSuccess('支付成功')
            that.cancel()
            // 更新用户信息
            this.$store.dispatch('GetInfo')
          } else {
            time = time + 3
            if(time >= 5 * 60) {
              that.$modal.msgError('支付超时')
              that.cancel()
            }
          }
        }
      }, 3000);
    },
    payPlatform() {
      if(!this.platformInfo.id) {
        this.$modal.msg('请选择服务套餐')
        return
      }
      if(!this.checked) {
        this.$modal.msg('请同意服务套餐购买协议')
        return
      }
      this.open = true
    },
    getplatformRightsList() {
      this.$modal.loading();
      platformRightsGetList({ businessType: this.businessType }).then(res => {
        this.$modal.closeLoading();
        this.platformRightsList = res.data
      })
    },
    handleClick(tab, event) {
      this.platformInfo = {}
      this.getplatformRightsList()
    },
    /** 查询平台权益订单列表 */
    getList() {
      this.loading = true;
      listPlatformRightsOrder(this.queryParams).then(response => {
        this.platformRightsOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.code = ''
      this.open = false;
      clearInterval(interval)
      this.getList();
    },
  }
};
</script>

<style lang="scss" scoped>
.list {
  padding: 40px;
  display: flex;
  gap: 32px 32px;
  margin-bottom: 32px;
  .item {
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    padding: 12px;
    width: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    border: 1px solid #d7dae2;
    border-radius: 4px;
  }
  .active {
    box-shadow: 0 2px 4px rgba(246, 102, 4, .12), 0 0 6px rgba(246 , 102, 4, .04);
    border: 1px solid #f66604;
  }
}
.money {
  color: #f66604;
  font-size: 18px;
  font-weight: 500;
}
.tips {
  font-family: PingFang-SC, PingFang-SC;
  font-size: 14px;
  color: rgba(0,0,0,0.5);
}
.actions {
  display: flex;
  justify-content: space-between;
  padding: 40px;
}
.pay-type {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 36px;
  img {
    cursor: pointer;
    width: 200px;
    height: auto;
  }
}
</style>
